package com.tuanzi.loan.web.bean.family;

import com.base.common.log.LogService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.starbaba.model.utils.JSONUtils;
import com.tuanzi.loan.business.entity.CurrentUser;
import com.tuanzi.loan.business.entity.family.LoanWholeSaleComment;
import com.tuanzi.loan.business.service.family.LargeAmountChannelManageService;
import com.tuanzi.loan.business.service.family.LoanWholeSaleCommentService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.vo.request.family.LoanWholeSaleCommentSearchRequest;
import com.tuanzi.loan.vo.view.family.CommRegionNewInfo;
import com.tuanzi.loan.vo.view.family.WholeSaleCityLimitInfo;
import com.tuanzi.loan.web.configuration.JSFInfoBean;
import com.tuanzi.server.loan_base.util.DateUtils;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class LoanWholeSaleCommentInfoBean extends JSFInfoBean<LoanWholeSaleComment> {
    private static final long serialVersionUID = 7413379055244548302L;

    @Autowired
    LoanWholeSaleCommentService loanWholeSaleCommentService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    LargeAmountChannelManageService largeAmountChannelManageService;

    public LoanWholeSaleCommentSearchRequest request = new LoanWholeSaleCommentSearchRequest();
    private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
    public List<String> weeklist = Lists.newArrayList();
    public List<String> reginlist = Lists.newArrayList();
    public String cityInfo = null;
    public Date statrtrequest;
    public Date endrequest;
    public List<WholeSaleCityLimitInfo> limitInfoList = Lists.newArrayList();
    private HashMap<String, WholeSaleCityLimitInfo> limitTempMap = Maps.newHashMap(); //用户保存最开始的设置数据

    @PostConstruct
    public void init(){
        String idStr = getParamFromRequest("id");
        if(StringUtils.isNotBlank(idStr)){
            try {
                $=loanWholeSaleCommentService.findLoanWholeSaleCommentById(NumberUtils.toLong(idStr));
                onEditTarget($);
                changeStatusToView();
            } catch (Exception e) {
                addErrorMessage("初始化异常");
                LogService.error("初始化异常",e);
            }
        }else{
            $ = new LoanWholeSaleComment();
            try {
                onCreateTarget();
                changeStatusToEdit();
            } catch (ParseException e) {
                addErrorMessage("初始化异常");
                LogService.error("初始化异常");
            }
        }
    }

    private void onEditTarget(LoanWholeSaleComment response) throws ParseException {
        endrequest=sdf.parse(response.getDowntime());
        statrtrequest = sdf.parse(response.getUppertime());
        request.setHas_weilidai("是".equals(response.getHas_weilidai()));
        request.setHas_estate("是".equals(response.getHas_estate()));
        request.setHas_car("是".equals(response.getHas_car()));
        request.setHouse_fund("是".equals(response.getHouse_fund()));
        request.setCredit("是".equals(response.getCredit()));
        request.setLife_insurance("是".equals(response.getLife_insurance()));
        request.setSocial_insurance("是".equals(response.getSocial_insurance()));
        request.setWaitui("是".equals(response.getWaitui()));
        request.setZhannei("是".equals(response.getZhannei()));

        if (Objects.nonNull(response.getOnlinedate())){
            Arrays.stream(response.getOnlinedate().split(",")).forEach(arr->weeklist.add(arr.trim()));
        }
        if (Objects.nonNull(response.getComm_regoin())){
            Arrays.stream(response.getComm_regoin().split(",")).forEach(arr->reginlist.add(arr.trim()));
        }
        cityInfo = response.getComm_regoin();
        String filterChannel = $.getFilterChannel();
        if(StringUtils.isNotBlank(filterChannel)){
            String[] split = filterChannel.split(",");
            request.setFilterChannel(Lists.newArrayList(split));
        }

        String cityLimit = response.getCityLimit();
        List<WholeSaleCityLimitInfo> cityLimitListInDb = JSONUtils.fromJsonArrayNew(cityLimit, WholeSaleCityLimitInfo.class);
        if(null != cityLimitListInDb && cityLimitListInDb.size() >0){
            limitInfoList.addAll(cityLimitListInDb);
        }

        limitInfoList.forEach(limitInfo -> limitTempMap.put(limitInfo.getCityName(), limitInfo));

        changeStatusToEdit();
    }

    public void onCreate(){
        $.setDowntime(sdf.format(endrequest));
        $.setUppertime(sdf.format(statrtrequest));
        $.setHas_weilidai(request.isHas_weilidai()?"是":"否");
        $.setHas_estate(request.isHas_estate()?"是":"否");
        $.setHas_car(request.isHas_car()?"是":"否");
        $.setHouse_fund(request.isHouse_fund()?"是":"否");
        $.setCredit(request.isCredit()?"是":"否");
        $.setLife_insurance(request.isLife_insurance()?"是":"否");
        $.setSocial_insurance(request.isSocial_insurance()?"是":"否");
        $.setWaitui(request.isWaitui()?"是":"否");
        $.setZhannei(request.isZhannei()?"是":"否");
        this.cityInfo = reginlist.toString().replace("[","").replace("]","");
        $.setComm_regoin(cityInfo);
        $.setOnlinedate(weeklist.toString().replace("[","").replace("]",""));
        List<String> filterChannel = request.getFilterChannel();

        if(null != filterChannel && filterChannel.size() > 0){
            String filterStr = StringUtils.join(filterChannel, ",");
            $.setFilterChannel(filterStr);
        }else{
            $.setFilterChannel(null);
        }

        //各地限量信息
        Integer totalNumber = $.getNumber();
        if(limitInfoList.size() > 0 &&  totalNumber != null){
            Integer tempNumber = 0;
            for (WholeSaleCityLimitInfo info : limitInfoList) {
                boolean isNull = info.getLimitValue() == null;
                if(isNull){
                    addErrorMessage("地区限量不能为空");
                    return;
                }

                tempNumber += info.getLimitValue();;
            }

            if(tempNumber > totalNumber){
                addErrorMessage("各地区累加不能超过总限制数量");
                return;
            }

            if(0 == tempNumber){ //限量全部设置 0，置空地区限量
                $.setCityLimit(null);
            }else{
                $.setCityLimit(JSONUtils.toJsonString(limitInfoList));
            }
        }else {
            $.setCityLimit(null);
        }

        if (Objects.nonNull($.getId())){
            updateLoanWholeComment($);
        }else{
            try {
                if (loanWholeSaleCommentService.saveLoanWholeSaleComment($) > 0)
                    addSuccessfullyMessage();
            }catch (Exception e){
                addErrorMessage("创建API失败\n"+e.getMessage());
            }
        }
        changeStatusToView();
    }

    private void onCreateTarget() throws ParseException {
        statrtrequest=sdf.parse("00:00");
        endrequest = sdf.parse("23:59");
        request.setWaitui(true);
        request.setZhannei(false);
        $.setNumber(100);
        $.setAvgprice(new BigDecimal(0.00));
        $.setOwnername(null);
        $.setType(null);
        $.setSort(0);
        $.setDowntime(sdf.format(endrequest));
        $.setUppertime(sdf.format(statrtrequest));
        weeklist.addAll(getWeek());
        $.setStatus(1);
        $.setApprovenum(0);
        String name = CurrentUser.get().getName();
        $.setCreator(name);
        $.setCreatedate(DateUtils.formatYyyyMMddToDate(DateUtils.getCurrentDate()));
        $.setUpdator(name);
        $.setCooperate("招商银行");
        $.setAmount(null);
        $.setUpdateTime(DateUtils.formatYyyyMMddHHmmssToDate(DateUtils.getCurrentTime()));
    }

    public void areaChange(){
        this.cityInfo = reginlist.toString().replace("[","").replace("]","");
        List<WholeSaleCityLimitInfo> limitTemp = new ArrayList<>();
        for (String regin : reginlist) {
            WholeSaleCityLimitInfo wholeSaleCityLimitInfo = limitTempMap.get(regin);
            if(null != wholeSaleCityLimitInfo){
                limitTemp.add(wholeSaleCityLimitInfo);
            }else{
                WholeSaleCityLimitInfo newLimitInfo = new WholeSaleCityLimitInfo();
                newLimitInfo.setCityName(regin);
                newLimitInfo.setLimitValue(0);
                limitTemp.add(newLimitInfo);
            }
        }

        this.limitInfoList = limitTemp;
    }

    private void updateLoanWholeComment(LoanWholeSaleComment loan){
        try {
            if (loanWholeSaleCommentService.updateLoanWholeSaleComment(loan)>0)
                addSuccessfullyMessage();
        } catch (Exception e) {
            addErrorMessage("更新数据失败");
            LogService.error("更新数据失败",e);
        }
    }

    public List<String> getCFrom(){
        return largeAmountChannelManageService.selectDistinctCFrom();
    }

    public List<String> getWeek(){
        return Arrays.asList("周日","周一","周二","周三","周四","周五","周六");
    }

    public List<CommRegionNewInfo> findAllRegionInfo(){
        return loanWholeSaleCommentService.findAllRegionInfo();
    }

}
